import { createSlice } from "@reduxjs/toolkit"
import type { TopListType, RankingDetailType,playlistType } from "./type"
import { getTopList, getRankingList } from "../service/ranking"
import { createAsyncThunk } from "@reduxjs/toolkit"
export const fetchTopListAction = createAsyncThunk(
  'getTopList',
  async (arg, { dispatch }) => {
    await getTopList().then((res) => {
      console.log(res)
      dispatch(changeTopListAction(res.list))
    })
  }
)
export const fetchRankingListAction = createAsyncThunk(
  'getRankingList',
  async (arg: { id: number }, { dispatch }) => {
    await getRankingList(arg.id).then((res) => {
      console.log(res)
      dispatch(changeRankingDetailAction(res))
      dispatch(changePlaylistAction(res.playlist))
    })
  }
)
type rankingState = {
    topList: TopListType[],
    rankingDetail: RankingDetailType[],
    currentIndex:number,
    playlist: playlistType
}

const initialState: rankingState = {
    topList: [],
    rankingDetail: [],
    currentIndex:0,
    playlist:{} as playlistType

}

export const rankingSlice = createSlice({
    name: 'ranking',
    initialState,
    reducers: {
        changeTopListAction(state, action) {
            state.topList = action.payload
        },
        changeRankingDetailAction(state, action) {
            state.rankingDetail = action.payload
        },
        changeCurrentIndexAction(state, action) {
            state.currentIndex = action.payload
        },
        changePlaylistAction(state, action) {
            state.playlist = action.payload
        },

    }
})

export const {changeTopListAction, changeRankingDetailAction, changeCurrentIndexAction, changePlaylistAction} = rankingSlice.actions    

export default rankingSlice.reducer